package com.yisu.expressway.api.web.controller;

import com.google.common.collect.Lists;
import com.yisu.expressway.api.core.service.IGoodsCategoryService;
import com.yisu.expressway.api.core.service.IGoodsInfoService;
import com.yisu.expressway.api.core.service.IGoodsSpecificationService;
import com.yisu.expressway.api.domain.request.GoodsInfoRequest;
import com.yisu.expressway.api.domain.response.GoodsDetailResponse;
import com.yisu.expressway.api.domain.response.GoodsInfoForBuyResponse;
import com.yisu.expressway.api.domain.response.GoodsListResponse;
import com.yisu.expressway.api.domain.vo.CategoryGoodsVo;
import com.yisu.expressway.api.domain.vo.GoodsDetailVo;
import com.yisu.expressway.api.domain.vo.GoodsInfoForBuyVo;
import com.yisu.expressway.api.domain.vo.goodsSpecification.SpecificationDetailVo;
import com.yisu.expressway.api.domain.vo.goodsSpecification.SpecificationInfoVo;
import com.yisu.expressway.ewf.common.enums.ResponseCode;
import com.yisu.expressway.ewf.common.web.JsonResult;
import com.yisu.expressway.ewf.entity.GoodsCategory;
import com.yisu.expressway.ewf.entity.GoodsSpecification;
import org.apache.calcite.linq4j.Linq4j;
import org.apache.calcite.linq4j.function.Predicate1;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 商品信息业务控制层
 * Created by zj on 2017/5/2.
 */
@RequestMapping("/goodsInfo")
@Controller
public class GoodsInfoController extends BaseController {
    @Resource
    private IGoodsInfoService iGoodsInfoService;
    @Resource
    private IGoodsSpecificationService iGoodsSpecificationService;
    @Resource
    private IGoodsCategoryService iGoodsCategoryService;

    /**
     * 获取模块数据
     *
     * @param token            token令牌， 可为空
     * @param goodsInfoRequest
     * @return json响应
     */
    @RequestMapping(value = "/getGoodsDetail", method = {RequestMethod.POST}, produces = "application/json; charset=utf-8")
    @ResponseBody
    public JsonResult getGoodsDetail(@RequestHeader(value = "X-Long-Token", required = false) String token, @RequestBody GoodsInfoRequest goodsInfoRequest) {
        JsonResult result = new JsonResult();
        GoodsDetailResponse goodsDetailResponse = new GoodsDetailResponse();
        GoodsDetailVo goodsDetailVo = new GoodsDetailVo();
        try {
            if (goodsInfoRequest.getCategoryCode() == null || goodsInfoRequest.getGoodsNo() == null || goodsInfoRequest.getSpecificationNo() == null) {
                return new JsonResult(ResponseCode.PARAMETER_ERROR.code, "参数不完整！");
            }
            goodsDetailVo = iGoodsInfoService.getGoodsDetail(goodsInfoRequest);
            if(!StringUtils.isEmpty(goodsDetailVo.getDetailsInfo()))
            {
                if(goodsDetailVo.getDetailsInfo().contains("<p"))
                {
                   List<String> imageStr=getImgStr(goodsDetailVo.getDetailsInfo());
                    goodsDetailVo.setDetailsInfo(StringUtils.join(imageStr,","));
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        goodsDetailResponse.setGoodsDetailVo(goodsDetailVo);
        result.setData(goodsDetailResponse);
        return result;
    }


    public static List<String> getImgStr(String htmlStr) {
        List<String> pics = Lists.newArrayList();
        String img = "";
        Pattern p_image;
        Matcher m_image;
        //     String regEx_img = "<img.*src=(.*?)[^>]*?>"; //图片链接地址
        String regEx_img = "<img.*src\\s*=\\s*(.*?)[^>]*?>";
        p_image = Pattern.compile
                (regEx_img, Pattern.CASE_INSENSITIVE);
        m_image = p_image.matcher(htmlStr);
        while (m_image.find()) {
            // 得到<img />数据
            img = m_image.group();
            // 匹配<img>中的src数据
            Matcher m = Pattern.compile("src\\s*=\\s*\"?(.*?)(\"|>|\\s+)").matcher(img);
            while (m.find()) {
                pics.add(m.group(1).replace("&quot;",""));
            }
        }
        return pics;
    }

    /**
     * 获取模块数据
     *
     * @param token            token令牌， 可为空
     * @param goodsInfoRequest
     * @return json响应
     */
    @RequestMapping(value = "/getGoodsInfoForBuy", method = {RequestMethod.POST}, produces = "application/json; charset=utf-8")
    @ResponseBody
    public JsonResult getGoodsInfoForBuy(@RequestHeader(value = "X-Long-Token", required = false) String token, @RequestBody GoodsInfoRequest goodsInfoRequest) {
        JsonResult result = new JsonResult();
        GoodsInfoForBuyResponse goodsInfoForBuyResponse = new GoodsInfoForBuyResponse();
        GoodsInfoForBuyVo goodsInfoForBuyVo = new GoodsInfoForBuyVo();
        List<SpecificationInfoVo> specificationInfoVos = Lists.newArrayList();
        try {
            //优先验证当前规格下是否存在二级规格，存在则获取二级规格第一商品
            List<GoodsSpecification> goodsSpecificationVos = iGoodsSpecificationService.getChildListByGoodsNoAndCategoryCode(goodsInfoRequest);
            if (!CollectionUtils.isEmpty(goodsSpecificationVos)) {
                GoodsSpecification firstModel = Linq4j.asEnumerable(goodsSpecificationVos).firstOrDefault();
                if (firstModel != null) {
                    goodsInfoRequest.setSpecificationNo(firstModel.getSpecificationNo());
                }
            }
            if (goodsInfoRequest.getCategoryCode() == null || goodsInfoRequest.getGoodsNo() == null || goodsInfoRequest.getSpecificationNo() == null) {
                return new JsonResult(ResponseCode.PARAMETER_ERROR.code, "参数不完整！");
            }
            GoodsDetailVo goodsDetailVo = iGoodsInfoService.getGoodsDetail(goodsInfoRequest);
            List<String> currentNodePath = Lists.newArrayList();
            if (goodsDetailVo != null) {
                goodsInfoForBuyVo.setCategoryCode(goodsDetailVo.getCategoryCode());
                goodsInfoForBuyVo.setBazaarPrice(goodsDetailVo.getBazaarPrice());
                goodsInfoForBuyVo.setGoodsNo(goodsDetailVo.getGoodsNo());
                goodsInfoForBuyVo.setImage(goodsDetailVo.getImage());
                goodsInfoForBuyVo.setName(goodsDetailVo.getName());
                goodsInfoForBuyVo.setPrice(goodsDetailVo.getPrice());
                goodsInfoForBuyVo.setSecondName(goodsDetailVo.getSecondName());
                goodsInfoForBuyVo.setSecondName(goodsDetailVo.getSecondName());
                String nodePath = iGoodsInfoService.selectNodePathByPrimaryKey(goodsInfoRequest.getSpecificationNo());
                if (!StringUtils.isEmpty(nodePath))
                    currentNodePath = Linq4j.asEnumerable((StringUtils.split(nodePath, ","))).toList();
            }
            List<String> groupNames = iGoodsInfoService.getSpecificationGroupNameByGoodsNoAndCategoryCode(goodsInfoRequest);
            if (!CollectionUtils.isEmpty(groupNames)) {
                List<GoodsSpecification> goodsSpecificationList = iGoodsInfoService.getSpecificationListByGoodsNoAndCategoryCode(goodsInfoRequest);
                for (final String groupNameItem : groupNames) {
                    SpecificationInfoVo specificationInfoVo = new SpecificationInfoVo();
                    List<SpecificationDetailVo> specificationDetailVos = Lists.newArrayList();
                    specificationInfoVo.setGropuName(groupNameItem);
                    //获取当前组名下的所有分类
                    List<GoodsSpecification> currentNodeDataList = Linq4j.asEnumerable(goodsSpecificationList).where(new Predicate1<GoodsSpecification>() {
                        @Override
                        public boolean apply(GoodsSpecification goodsSpecification) {
                            return goodsSpecification.getBelongGroupName().equals(groupNameItem);
                        }
                    }).toList();
                    if (!CollectionUtils.isEmpty(currentNodeDataList)) {
                        for (GoodsSpecification item : currentNodeDataList) {

                            SpecificationDetailVo specificationDetailVo = new SpecificationDetailVo();
                            specificationDetailVo.setName(item.getName());
                            specificationDetailVo.setParentId(item.getParentId());
                            specificationDetailVo.setSpecificationNo(item.getSpecificationNo());
                            System.out.println("-----" + currentNodePath.get(0) + "-------------------");
                            System.out.println("-----" + String.valueOf(item.getSpecificationNo()) + "-------------------");
                            if (currentNodePath.contains(item.getSpecificationNo() + "")) {
                                specificationDetailVo.setChecked(true);
                            }
                            specificationDetailVos.add(specificationDetailVo);
                        }
                        specificationInfoVo.setSpecificationDetailVos(specificationDetailVos);
                    } else {
                        continue;
                    }
                    specificationInfoVos.add(specificationInfoVo);
                }
                goodsInfoForBuyVo.setSpecificationInfoVos(specificationInfoVos);
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        goodsInfoForBuyResponse.setGoodsInfoForBuyVo(goodsInfoForBuyVo);
        result.setData(goodsInfoForBuyResponse);
        return result;
    }


    /**
     * 通过分类获取分类推荐商品列表
     *
     * @param token            token令牌， 可为空
     * @param goodsInfoRequest
     * @return json响应
     */
    @RequestMapping(value = "/getGoodsListByCategoryCode", method = {RequestMethod.POST}, produces = "application/json; charset=utf-8")
    @ResponseBody
    public JsonResult getGoodsListByCategoryCode(@RequestHeader(value = "X-Long-Token", required = false) String token, @RequestBody GoodsInfoRequest goodsInfoRequest) {
        JsonResult result = new JsonResult();
        GoodsListResponse goodsListResponse = new GoodsListResponse();
        List<CategoryGoodsVo> categoryGoodsVos = Lists.newArrayList();
        try {
            if (StringUtils.isEmpty(goodsInfoRequest.getCategoryCode())) {
                return new JsonResult(ResponseCode.PARAMETER_ERROR.code, "参数不完整！");
            }
            GoodsCategory goodsCategory = iGoodsCategoryService.getGoodsCategoryByCategoryCode(goodsInfoRequest.getCategoryCode());
            if (goodsCategory != null) {
                List<String> nodePathArry = Linq4j.asEnumerable(StringUtils.split(goodsCategory.getNodePath(), ",，")).toList();
                if (nodePathArry.size() >= 2) {
                    goodsInfoRequest.setCategoryNodePath(goodsCategory.getNodePath());
                    categoryGoodsVos = iGoodsInfoService.getGoodsListByNodePath(goodsInfoRequest);
                } else {
                    categoryGoodsVos = iGoodsInfoService.getGoodsListByCategoryCode(goodsInfoRequest);
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        goodsListResponse.setCategoryGoodsVos(categoryGoodsVos);
        result.setData(goodsListResponse);
        return result;
    }

    /**
     * 通过分类获取分类推荐商品列表
     *
     * @param token            token令牌， 可为空
     * @param goodsInfoRequest
     * @return json响应
     */
    @RequestMapping(value = "/getGoodsListByQuery", method = {RequestMethod.POST}, produces = "application/json; charset=utf-8")
    @ResponseBody
    public JsonResult getGoodsListByQuery(@RequestHeader(value = "X-Long-Token", required = false) String token, @RequestBody GoodsInfoRequest goodsInfoRequest) {
        JsonResult result = new JsonResult();
        GoodsListResponse goodsListResponse = new GoodsListResponse();
        List<CategoryGoodsVo> categoryGoodsVos = Lists.newArrayList();
        try {
            if (StringUtils.isEmpty(goodsInfoRequest.getKeyword())) {
                return new JsonResult(ResponseCode.PARAMETER_ERROR.code, "请输入有效的检索条件！");
            }
            categoryGoodsVos = iGoodsInfoService.getGoodsListByQuery(goodsInfoRequest);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        goodsListResponse.setCategoryGoodsVos(categoryGoodsVos);
        result.setData(goodsListResponse);
        return result;
    }
}